import axios from 'axios';
import {Message, Loading } from 'element-ui';
import store from '../store';

const TOKEN_INVALID = 'Token认证失败，请重新登录';
const NETWORK_ERROR = '网络请求异常，请重新登录';
const loading = {
  loadingInstance: null,
  open() {
    if (this.loadingInstance == null) {
      this.loadingInstance = Loading.service({
        target: 'body',
        background: 'rgba(0,0,0,0.4)',
        text: '加载中',
      });
    }
  },
  close() {
    if (this.loadingInstance != null) {
      this.loadingInstance.close();
    }
    this.loadingInstance = null;
  },
};
// 创建axios实例对象
const service = axios.create({
  // 请求的公共接口地址
  baseURL: process.env.VUE_APP_BASE_API,
  // 请求的超时时间
  // timeout : 50000
});
// 创建请求拦截器
service.interceptors.request.use((config) => {
  loading.open();
  const token = store.state.userInfo.token || '';
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
}, (error) => {
  loading.close();
  return Promise.reject(error);
});

// 创建响应拦截器
service.interceptors.response.use(function (response) {
  loading.close();
  const { code, data, msg } = response.data;
  if (code === 200) {
    return data;
  } if (code === 500001) {
    Message({
      type: 'error', // success error warning
      message: TOKEN_INVALID,
    });
    store.dispatch('handlelogout');
    return Promise.reject(TOKEN_INVALID);
  }
  Message({
    type: 'error',
    message: msg || NETWORK_ERROR,
  });
  return Promise.reject(msg || NETWORK_ERROR);
}, (error) => {
  loading.close();
  return Promise.reject(error);
});

function request(options) {
  options.method = options.method || 'GET';
  if (options.method.toLowerCase() == 'get') {
    options.params = options.data;
  }
  return service(options);
}
// 导出axios实例对象
export default request;
